package com.rachel.materialdemo.common;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Created by zhengshaorui on 2017/8/23.
 */

public class RBaseViewholder extends RecyclerView.ViewHolder {

    private SparseArray<View> mViewSparseArray; //用来保存 itemview；
    private View mConserView;
    public RBaseViewholder(View itemView) {
        super(itemView);
        mViewSparseArray = new SparseArray<>();
        mConserView = itemView;
    }

    /**
     * 这里相当于在 oncreateViewholder 中，设置好数据，然后返回
     * @param context
     * @param layoutid
     * @param parent
     * @return
     */
    public static RBaseViewholder getViewHolder(Context context,int layoutid, ViewGroup parent){
        View view = LayoutInflater.from(context).inflate(layoutid,parent,false);
        RBaseViewholder viewholder = new RBaseViewholder(view);
        return viewholder;
    }

    public static RBaseViewholder getViewHolder(Context context, View itemView){

        RBaseViewholder viewholder = new RBaseViewholder(itemView);
        return viewholder;
    }

    public View getConserView(){
        return mConserView;
    }


    /**
     * getItemview，通过 id获取view
     * @param resId
     * @return
     */
    public View getItemView(int resId){
        View view = mViewSparseArray.get(resId);
        if (view == null){
            view = mConserView.findViewById(resId);
            mViewSparseArray.put(resId,view);
        }
        return view;
    }



    /**
     * 设置数据，直接通过id获取到view，然后设置数据
     * @param resId
     * @param data
     * @return
     */
    public RBaseViewholder setText(int resId,String data){
        TextView textView = (TextView) getItemView(resId);
        textView.setText(data);
        return this;
    }

    /**
     * 设置数据，直接通过id获取到view，然后设置数据
     * @param resId
     * @return
     */
    public RBaseViewholder setImageResId(int resId,int id){
        ImageView imageView = (ImageView) getItemView(resId);
        imageView.setImageResource(id);
        return this;
    }


}
